const bodyParser =require('body-parser');
var chokidar = require('chokidar')
var fs = require('fs');
var path=require('path');
function resolve (dir) {
    return path.join(__dirname, '..', dir)
}
module.exports=function(app){
    //const express = require('express');
    //const app = express();
    app.use(bodyParser.urlencoded({ limit: '50mb',extended: true }))
    app.use(bodyParser.json({limit: '50mb'}))

    function getmock(){
        var mock={};
        if(fs.existsSync(resolve('mock'))){
            fs.readdirSync(resolve('mock')).forEach(file=>{
                var u=resolve('mock/'+file)
                delete require.cache[u];
                Object.assign(mock,require('../mock/'+file))
            })
        }
        return mock;
    }
    function createMockHandler(method, path, value) {
        return function mockHandler(...args) {
        const res = args[1];
        if (typeof value === 'function') {
            value(...args);
        } else {
            res.json(value);
        }
        };
    }
    function parseKey(key) {
        let method = 'get';
        let path = key;
    
        if (key.indexOf(' ') > -1) {
        const splited = key.split(' ');
        method = splited[0].toLowerCase();
        path = '/mock'+splited[1];
        }
    
        return { method, path };
    } 
    function applyMock(app){
        
        const mock=getmock(); 
        var mockRules=[]
        Object.keys(mock).forEach(function(key){
            const keyParsed = parseKey(key);
            mockRules.push({
                path: keyParsed.path,
                method: keyParsed.method,
                target: mock[key],
            });
        })
        mockRules.forEach(function(mock){
            app[mock.method](
                mock.path,  
                //mock.target
                createMockHandler(mock.method, mock.path, mock.target),
            );
        })
        
        
        var watcher =chokidar.watch([resolve('mock/')],{
            ignored: /node_modules/,
            ignoreInitial: true,
        })
        watcher.on('change',function(path){
            //console.log('change');
            //console.log('app._router.stack.length',app._router.stack.length);
            watcher.close();
            var stack=app._router.stack;
            var u=stack.filter(function(i){
                return /mock/g.test(i.regexp.toString());
            });
            //console.log(u);
            var _in=-1;
            stack.forEach(function(item,index){
                if(/mock/g.test(item.regexp.toString()) && _in==-1){
                    _in=index;
                }
            })
            //console.log('_in',_in,'length',u.length)
            app._router.stack.splice(_in,u.length);
            //console.log('app._router.stack.length change',app._router.stack.length)
            applyMock(app);
        })
        //console.log('app._router.stack.length',app._router.stack.length);
        
    }




    

    applyMock(app);


//app.listen(3002);
}
